<?php namespace Admin\Controller;
/*
 * 文章管理控制器
 * */
class ArticleController extends CommonController{
	protected $db;

    public function __construct(){
    	$this->db = new \Common\Model\Article;
	}
	/*
	 * 首页
	 * */
	public function index(){
		//总计几条
		$count = $this->db->where("is_recycle",0)->count();
		$page = Page::row(8)->make($count);
		//获得所有数据
		$data = Db::table('article')->join('category','article.category_cid','=','category.cid')->field("category.cname","article.aid","article.title")->where("is_recycle",0)->limit(page::limit())->get();

View::with("data",$data);
View::with("page",$page);
		View::make();
	}
	/*
	 * 添加页面
	 * */
	public function add(){
		
		if(IS_POST){
		    if(!$this->db->store()){
				//添加失败
				View::error($this->db->getError());
			}else{
				//添加成功
				View::success("添加成功",U("Article/index"));
			}
		}
		//获得所有标签名
		$tagdata =Db::table("tag")->get();
		View::with("tagdata",$tagdata);
		//获得所有分类数据
		$catedata = Db::table("category")->get();
		//变成树状结构
		$catedata = Data::tree($catedata,"cname");
		View::with("catedata",$catedata);
		//载入模板
		View::make();
	}
	/*
	 * 编辑文章
	 * */
	 public function edit(){
	 	$aid =Q("get.aid",0,'intval');
		if(IS_POST){
		  if(!$this->db->edit($aid)){
				//添加失败
				View::error($this->db->getError());
			}else{
				//添加成功
				View::success("编辑成功",U("Article/index"));
			}
			
		}
		//获得旧数据
		$olddata = Db::table('article')->join('article_data','aid','=','article_aid')->where("aid",$aid)->first();
		View::with("olddata",$olddata);
		//获得标签表的数据
		$tagdata = Db::table("tag")->get();
		View::with("tagdata",$tagdata);
		//获得所有分类数据
		$catedata = Db::table("category")->get();
		//变成树状结构
		$catedata = Data::tree($catedata,"cname");
		View::with("catedata",$catedata);
		//文章标签中间表获得当前的标签id
		//获取单一字段
		$tids = Db::table("article_tag")->where("article_aid",$aid)->lists("tag_tid");
		View::with("tids",$tids);
	 	//载入模板
		View::make();
	 }
	/*
	 * 放入回收站
	 * */
	public function del(){
		$aid =Q("get.aid",0,'intval');
		 //将文章表里的is_recycle字段值变成1；
	    $this->db->where("aid",$aid)->update(array("is_recycle"=>1));
		$this->success("删除成功",U("index"));
	}
	/*
	 * 回收站
	 * */
	public function recycle(){
		//总计几条
		$count = $this->db->where("is_recycle",1)->count();
		$page = Page::row(8)->make($count);
		//获得所有数据
		$data = Db::table('article')->join('category','article.category_cid','=','category.cid')->field("category.cname","article.aid","article.title")->where("is_recycle",1)->limit(page::limit())->get();

View::with("data",$data);
View::with("page",$page);
		View::make();
	}
	/*
	 * 从回收站还原
	 * */
	 public function  restore(){
	 	$aid =Q("get.aid",0,'intval');
	 //将文章表里的is_recycle字段值变成0,
		 $this->db->where("aid",$aid)->update(array("is_recycle"=>0,));
		$this->success("还原成功",U("recycle"));
	 }
	/*
	 * 彻底删除 
	 * */ 
	public function deletes(){
		$aid =Q("get.aid",0,'intval');
		$this->db->deletes($aid);
		$this->success("删除成功",U("recycle"));
	}
	
	
}